package com.hnue.k60b.newapplication;

import java.util.List;

import com.hnue.k60b.adapter.CatagoryAdapter;
import com.hnue.k60b.models.RssItem;
import com.hnue.k60b.utils.RssParser;
import com.hnue.k60b.utils.Variables;

import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.ListView;

public class CatagoriActivity extends ListActivity {

	private int paper;
	private ProgressDialog diaglog;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// khai báo 1 bundle để getextra
		// paper lưu giữ vị trí của trên báo trong danh sách khi click vào sẽ dc
		// trả lại cho paper
		// truyền paper trong hàm settitle sẽ đặt đúng tên báo cho title của
		// activity mới
		Bundle bundle = getIntent().getExtras();
		paper = bundle.getInt(Variables.PAPER);
		setTitle(Variables.PAPERS[paper]);
		CatagoryAdapter adapter = new CatagoryAdapter(this,
				Variables.ICONS[paper], Variables.CATAGORIES[paper]);
		setListAdapter(adapter);
	}

	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		super.onListItemClick(l, v, position, id);
		int key = paper * 1000 + position;
		if (Variables.newmap.get(key) == null) {
			diaglog = ProgressDialog.show(this, "", "Đang tải "
					+ Variables.CATAGORIES[paper][position]);
			new CategoryTask().execute(position);

		} else {
			Intent intent = new Intent(CatagoriActivity.this,
					NewListActivity.class);
			intent.putExtra(Variables.PAPER, paper);
			intent.putExtra(Variables.CATAGORY, position);
			startActivity(intent);
		}

	}

	class CategoryTask extends AsyncTask<Integer, Void, Void> {
		private int position;

		@Override
		protected void onPostExecute(Void result) {
			if (diaglog != null) {
				diaglog.dismiss();
			}
			Intent intent = new Intent(CatagoriActivity.this,
					NewListActivity.class);
			intent.putExtra(Variables.PAPER, paper);
			intent.putExtra(Variables.CATAGORY, position);
			startActivity(intent);
			super.onPostExecute(result);
		}

		@Override
		protected Void doInBackground(Integer... params) {
			position = params[0];
			RssParser parser = new RssParser();
			int key = paper * 1000 + position;
			List<RssItem> items = parser
					.getnewlist(Variables.LINKS[paper][position]);
			Variables.newmap.put(key, items);
			return null;
		}

	}
}
